import { WebSocketGateway, SubscribeMessage, MessageBody, WebSocketServer, ConnectedSocket } from '@nestjs/websockets';
import { WebsocketService } from './websocket.service';
import { Server, Socket } from 'socket.io'
import { WsAuthDto } from './webscoket.dto';
import { Body, UseGuards } from '@nestjs/common';
import { SocketEncryptGuard, SocketJwtGuard, encryptResponse } from './websocket.guard';
import { validateJwt } from 'src/app/auth/app.strategy';
import { RedisService } from '@liaoliaots/nestjs-redis';
import Redis from 'ioredis';
import { OnEvent } from '@nestjs/event-emitter';

@WebSocketGateway({
	allowEIO3:true,
	cors:{
		origin:'*'
	}
})
export class WebsocketGateway {
	redis:Redis
	constructor(
		private readonly websocketService: WebsocketService,
		private readonly redisService: RedisService,
	) {
		this.redis = this.redisService.getClient();
	}

	count=0

	@WebSocketServer() server: Server

	@UseGuards(SocketJwtGuard)
	handleConnection(client: Socket) {
		let validate=validateJwt(client.handshake.auth["Authorization"])
		if(validate){
			this.redis.set(`socket_${validate._id}`,client.id)
			// setInterval(()=>{
			// 	this.server.to(client.id).emit("message","后端保持通信"+this.count)
			// 	this.count++
			// },2000)
		}else{
			client.disconnect()
		}
	}

	handleDisconnect(client: Socket) {
		let validate=validateJwt(client.handshake.auth["Authorization"])
		if(validate){
			this.redis.del(`socket_${validate._id}`,client.id)
		}
		// 在这里处理客户端断开连接的逻辑
		console.log('客户端已断开连接',client.id);
	}

	@OnEvent('websocket.send.change')
	async sendToClientChange(event: any){
		let clientId=await this.redis.get(`socket_${event._id}`)
		if(clientId){
			let res=encryptResponse({data:event.change,apiSecret:event.apiSecret})
			this.server?.to(clientId).emit("change",res)
		}
	}

	@OnEvent('websocket.send.logout')
	async sendToClientLogout(event: any){
		let clientId=await this.redis.get(`socket_${event._id}`)
		if(clientId){
			let res=encryptResponse({data:event.data,apiSecret:event.apiSecret})
			this.server?.to(clientId).emit("logout",res)
		}
	}
}
